package Engine.Utils;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * Class with some methods for image loading and handling.
 * @author Lueko
 *
 */
public abstract class ImageHandler {
	
    /**
     * Loads an image of a given path.
     * @param path Path of the image.
     * @return A BufferedImage.
     */
	public static BufferedImage load(String path) {
		try {
			return ImageIO.read(ImageHandler.class.getResource(path));
		} catch(IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * Splits an image with a specified size.
	 * @param map BufferedImage to split.
	 * @param sizeX Number of subimages in x axis.
	 * @param sizeY Number of subimages in y axis.
     * @param width Width of a splitted image.
     * @param height Height of a splitted image.
	 * @return A BufferedImage array.
	 */
	public static BufferedImage[][] splitImageMap(BufferedImage map, int sizeX, int sizeY,
			int width, int height) {
		if(sizeX <= 0 || sizeY <= 0 || width <= 0 || height <= 0 || 
				sizeX * width > map.getWidth() || sizeY * height > map.getHeight()) {
			return null;
		}
		
		BufferedImage[][] images = new BufferedImage[sizeY][sizeX];

        for(int y = 0; y < sizeY; y++) {
            for(int x = 0; x < sizeX; x++) {
				images[y][x] = map.getSubimage(x * width, y * height, width, height);
			}
		}
		
		return images;
	}
	
	/**
	 * Splits an image.
	 * @param map BufferedImage to split.
	 * @param width Width of a splitted image.
	 * @param height Height of a splitted image.
	 * @return A BufferedImage array.
	 */
	public static BufferedImage[][] splitImageMap(BufferedImage map, int width, int height) {
	    int sizeX = map.getWidth() / width;
	    int sizeY = map.getHeight() / height;
	    
        BufferedImage[][] images = new BufferedImage[sizeY][sizeX];

        for(int y = 0; y < sizeY; y++) {
            for(int x = 0; x < sizeX; x++) {
                images[y][x] = map.getSubimage(x * width, y * height, width, height);
            }
        }
        
        return images;
    }
}
